package org.alicuu.ioc;

import org.alicuu.ioc.reader.ClassInfo;
import org.alicuu.ioc.reader.ClassPathClassReader;
import org.alicuu.ioc.reader.ClassReader;
import org.alicuu.ioc.reader.JarClassReader;
import org.alicuu.toolkit.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.stream.Stream;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/05
 * Time: 09:39
 */
public final class DynamicContext {
    private static final Logger log = LoggerFactory.getLogger(DynamicContext.class);

    private static final ClassReader classPathClassReader = new ClassPathClassReader();
    private static final ClassReader jarReader = new JarClassReader();

    private static boolean isJarContext = false;

    public DynamicContext() {
    }

    public static void init(Class<?> clazz) {
        String rs = clazz.getResource("").toString();
        if (rs.contains(".jar"))
            isJarContext = true;
    }

    public static Stream<ClassInfo> recursionFindClasses(String packageName) {
        return getClassReader(packageName).getClass(packageName, true).stream();
    }

    public static ClassReader getClassReader(String packageName) {
        if (isJarPackage(packageName))
            return jarReader;
        return classPathClassReader;
    }

    private static boolean isJarPackage(String packageName) {
        if (StringUtil.isBlank(packageName))
            return false;
        try {
            packageName = packageName.replace(".", "/");
            Enumeration<URL> dirs = DynamicContext.class.getClassLoader().getResources(packageName);
            if (dirs.hasMoreElements()) {
                String url = dirs.nextElement().toString();
                return url.contains(".jar!") || url.contains(".zip");
            }
        } catch (IOException e) {
            log.error("", e);
        }
        return false;
    }

    public static boolean isIsJarContext() {
        return isJarContext;
    }
}
